/**
 * @class common.base.object
 * 所有对象的基类
 */
define(function (require) {
    require('lazyload');
    require('jq_cookie');
    require('layer_ui');

    $.fn = _.extend($.fn, {
        serializeJson: function () {
            var arr = $(this).serializeArray(),
                result = {};
            for (var i = 0; i < arr.length; i++) {
                result[arr[i].name] = arr[i].value;
            }
            return result;
        },
        hidden: function (name, val) {
            $(this).append(_.sprintf("<input type='hidden' name='%s' value='%s'/>", name, val));
        },
        uploader: function (options) {
            var settings = {
                btnid: $(this).attr('id'),
                action_url: '',
                input_id: 'J_img',
                input_name: 'img',
                multiple: false,
                showMessage: function (message) {
                    $.pinphp.tip({
                        content: message,
                        icon: 'error'
                    });
                },
                onSubmit: function (id, fileName) {
                },
                onComplete: function (id, fileName, result) {
                    if (result.status == '1') {
                        $('#' + settings.input_id).val(result.data);
                    }
                    else {
                        $.pinphp.tip({
                            content: result.msg,
                            icon: 'error'
                        });
                    }
                }
            };
            if (options) {
                $.extend(settings, options);
            }
            new qq.FileUploaderBasic({
                allowedExtensions: [],
                button: document.getElementById(settings.btnid),
                action: settings.action_url,
                inputName: settings.input_name,
                forceMultipart: true, //用$_FILES
                messages: {
                    typeError: '不允许上传的文件类型！',
                    sizeError: '文件大小不能超过{sizeLimit}！',
                    minSizeError: '文件大小不能小于{minSizeLimit}！',
                    emptyError: '文件为空，请重新选择！',
                    noFilesError: '没有选择要上传的文件！',
                    onLeave: '正在上传文件，离开此页将取消上传！'
                },
                showMessage: settings.showMessage,
                onSubmit: settings.onSubmit,
                onComplete: settings.onComplete
            });
        }
    });

    var BaseObject = function () {
        var _this = this;
        if (_.empty(window.OBJECT_ID)) {
            window.OBJECT_ID = 0;
        }
        if (_.empty(this.id)) {
            this.id = this.__ID();
        }
        BaseObject.prototype.el = '#' + _this.id;
        var result = this.initialize.apply(this, arguments);
        //this.bindEvents();
        if (_.empty(window.Z_INDEX)) {
            window.Z_INDEX = 1000;
        }
        return result;
    };
    BaseObject.prototype.__ID = function () {
        return 'COMPONENT_' + window.OBJECT_ID++;
    };
    /**
     * 实现子类继承父类
     * @param {Object} params 一个含属性、方法的对象
     * @return {Object} 一个继承的类
     */
    BaseObject.extend = function (protoProps, staticProps) {
        var parent = this;
        var child;
        if (protoProps && _.has(protoProps, 'constructor')) {
            child = protoProps.constructor;
        }
        else {
            child = function () {
                return parent.apply(this, arguments);
            };
        }
        _.extend(child, parent, staticProps);

        var Surrogate = function () {
            this.constructor = child;
        };
        Surrogate.prototype = parent.prototype;
        child.prototype = new Surrogate;
        if (protoProps) {
            _.extend(child.prototype, protoProps);
        }
        child.__super__ = parent.prototype;
        return child;
    };
    BaseObject.prototype.bindEvents = function () {

    };
    BaseObject.prototype.initialize = function () {
    };
    /**
     * 模板渲染，是对_.template的封装
     * @param {String} tpl 传递模板文件，如：require('text!./templates/xxx.html');
     * @param {Object} data 模板文件里面用到的值
     * @param {String} $wrap 如果设置，则把模板编译内容以html或append方式插入到该选择符内
     * @param {String} method 可选参数：html,append
     */
    BaseObject.prototype.render = function (tpl, data, $wrap, method) {
        var html = _.template(tpl, _.extend({}, {
            _id: this.id
        }, data));
        if ($wrap) {
            method = method == undefined ? 'html' : method;
            switch (method) {
                case 'append':
                    $wrap.append(html);
                    break;
                case 'html':
                default:
                    $wrap.html(html);
            }
        }
        return html;
    };
    BaseObject.prototype.setSelectionRange = function (input, selectionStart, selectionEnd) {
        selectionEnd = selectionStart || selectionEnd;
        if (input.setSelectionRange) {
            input.focus();
            input.setSelectionRange(selectionStart, selectionEnd);
        }
        else if (input.createTextRange) {
            var range = input.createTextRange();
            range.collapse(true);
            range.moveEnd('character', selectionEnd);
            range.moveStart('character', selectionStart);
            range.select();
        }
    };
    /**
     * 获取当前组件内的dom对象，是对$()的封装
     * @method $
     * @param {String} selector 同$()参数写法
     */
    BaseObject.prototype.$ = function (selector) {
        var _this = this;
        if ($('#' + _this.id).size() > 0) {
            _this.el = '#' + _this.id;
        }
        else {
            _this.el = 'body';
        }

        var _selector = [],
            res = _.explode(',', selector);
        _.each(res, function (val, key) {
            _selector.push(_this.el + ' ' + val);
        });
        return $(_.implode(',', _selector));
    };
    /**
     * 重新计算主体页面一些dom元素大小
     */
    BaseObject.prototype.appResize = function () {
        var height = document.documentElement.clientHeight;
        $('#main_page_wrap').height(height - 53);
        $('.app_content .pagination_wrap').width($('.app_content').width() - 12);
        $('#main_page_wrap').scroll(function () {
            if ($('.app_scroll_box').height() - $(this).height() - 20 < $(this).scrollTop()) {
                $('.pagination_wrap').removeClass('fixed');
                $('.app_scroll_box').addClass('end');
            }
            else {
                $('.pagination_wrap').addClass('fixed');
                $('.app_scroll_box').removeClass('end');
            }
        });
        $('.sub-menu li').removeClass('current');
        if (!_.in_array(_global.m, ['mp_page', 'goods'])) {
            var sel = '.sub-menu a[data-m="' + _global.m + '"][data-a="' + _global.a + '"]';
            if (_global.type != "") {
                sel += '[data-type="' + _global.type + '"]';
            }
            else {
                sel += '[data-type=""]';
            }
            $(sel).parents('li').addClass('current');
        }
    };
    BaseObject.prototype.lazyload = function () {
        $('img').lazyload({
            //placeholder: _global.static_url + "usercenter/images/loader.gif"
        });
    };
    BaseObject.prototype.getDataContent = function (data_type, data_content, data_id) {
        if (_.in_array(data_type, ['text', 'image', 'activity'])) {
            return data_content;
        }
        if (_.in_array(data_type, ['tuwen'])) {
            if (_.isString(data_content)) {
                data_content = _.json_decode(data_content);
            }
            return data_content;
        }
    };
    BaseObject.prototype.validate = function (params) {
        var _this = this;
        if (_.empty(params)) {
            params = {};
        }
        if (_.empty(params.form)) {
            params.form = $('form');
        }
        params.form.validate({
            onfocusout: false,
            errorClass: 'validate-wrong',
            invalidHandler: function (event, validator) {
                var errorList = validator.errorList;
                if (_.empty(errorList)) {
                    return;
                }
                var message = null;
                if (errorList[0].message == '必选字段') {
                    message = '请输入' + $(errorList[0].element).attr('placeholder');
                }
                else {
                    message = $(errorList[0].element).attr('placeholder') + ':' + errorList[0].message
                }
                if (message) {
                    if (params.msg_type == 'tips') {
                        layer.tips(message, $(errorList[0].element)[0], {
                            tips: 3
                        });
                    }
                    else {
                        layer.msg(message);
                    }
                }
            },
            submitHandler: function (form) {
                if (params.fn) {
                    params.fn(params.form.serializeJson());
                }
            }
        });
    };
    return BaseObject;
});